package com.ytjj.quartz.service;

import com.ytjj.qmyx.mall.mapper.PlatformStrictProfitMapper;
import com.ytjj.qmyx.mall.model.PlatformStrictProfit;
import com.ytjj.qmyx.users.client.AdminClient;
import com.ytjj.qmyx.users.mapper.UsersInfoMapper;
import com.ytjj.qmyx.users.model.UsersBalanceRecordStatistics;
import com.ytjj.qmyx.users.model.UsersInfo;
import com.ytjj.qmyx.users.model.UsersInfoExample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@RefreshScope
public class PlatformStrictInfoService {
    @Resource
    private PlatformStrictProfitMapper platformStrictProfitMapper;
    @Resource
    private UsersInfoMapper usersInfoMapper;
    @Autowired
    private AdminClient adminClient;
    @Value("${incomeRankDayBaseValue:300}")
    private String incomeRankDayBaseValue;//达人收益排行规则 1-按收益来排行  2-按测评数来

    /**
     * 达人测评曝光量 + 浏览量
     */
    public void runTaskByExposureNumAndBrowseNumDay() {
        UsersInfoExample usersInfoExample = new UsersInfoExample();
        usersInfoExample.createCriteria().andIsQualityEqualTo(1);
        long count = usersInfoMapper.countByExample(usersInfoExample);
        if (count <= 0) {
            return;
        }
        //查询大数据曝光量
        adminClient.scheduleTask();
    }

    /**
     * 达人收入占比
     */
    public void runTaskByDynamicIncomeRank() {
        UsersInfoExample usersInfoExample = new UsersInfoExample();
        usersInfoExample.createCriteria().andIsQualityEqualTo(1);
        List<UsersInfo> usersInfoList = usersInfoMapper.selectByExample(usersInfoExample);

        List<UsersBalanceRecordStatistics> list = usersInfoMapper.selectDynamicIncomeAmount("EVALUATION_COMMISSION");
        if (CollectionUtils.isEmpty(list)) {
            usersInfoList.stream().forEach(item -> {
                PlatformStrictProfit profit = platformStrictProfitMapper.selectByUserId(item.getId());
                if (null == profit) {
                    profit = new PlatformStrictProfit();
                }
                profit.setUserId(item.getId());
                profit.setIncomeRank(1);
                if (null == profit.getId()) {
                    platformStrictProfitMapper.insertSelective(profit);
                }else {
                    platformStrictProfitMapper.updateByPrimaryKey(profit);
                }
            });
            return;
        }
        calculationIncomeRank(usersInfoList);
//        usersInfoList.stream().forEach(item -> {
//            for (int i = 0; i < list.size(); i++) {
//                PlatformStrictProfit profit = platformStrictProfitMapper.selectByUserId(item.getId());
//                if (null == profit) {
//                    profit = new PlatformStrictProfit();
//                }
//                profit.setUserId(item.getId());
//                if (item.getId().equals(list.get(i).getUserId())) {
//                    if (i == 0) {
//                        profit.setIncomeRank(99.0);
//                    }else if (i == list.size() - 1) {
//                        profit.setIncomeRank(1.0);
//                    }else {
//                        BigDecimal rank = new BigDecimal(i).divide(new BigDecimal(list.size()), 2, BigDecimal.ROUND_HALF_UP);
//                        profit.setIncomeRank(new BigDecimal(1).subtract(rank).multiply(new BigDecimal(100)).doubleValue());
//                    }
//
//                }else {
//                    profit.setIncomeRank(1.0);
//                }
//                profit.setUpdateTime(new Date());
//                if (null == profit.getId()) {
//                    platformStrictProfitMapper.insertSelective(profit);
//                }else {
//                    platformStrictProfitMapper.updateByPrimaryKey(profit);
//                }
//            }
//        });
    }

    /**
     * 计算用户收益排行占比
     * 最新公式：用户收入/基数
     * 当用户收入=0的时候，排行占比=0%
     */
    private void calculationIncomeRank(List<UsersInfo> usersInfoList) {
        List<Integer> userIds = usersInfoList.stream().map(UsersInfo::getId).collect(Collectors.toList());
        List<UsersBalanceRecordStatistics> list = usersInfoMapper.selectDynamicIncomeAmountByUserIds("EVALUATION_COMMISSION", userIds);
        if (CollectionUtils.isEmpty(list)) {
            usersInfoList.stream().forEach(item -> {
                PlatformStrictProfit profit = platformStrictProfitMapper.selectByUserId(item.getId());
                if (null == profit) {
                    profit = new PlatformStrictProfit();
                }
                profit.setUserId(item.getId());
                profit.setIncomeRank(1);
                if (null == profit.getId()) {
                    platformStrictProfitMapper.insertSelective(profit);
                }else {
                    platformStrictProfitMapper.updateByPrimaryKey(profit);
                }
            });
            return;
        }
        usersInfoList.stream().forEach(item -> {
            PlatformStrictProfit profit = platformStrictProfitMapper.selectByUserId(item.getId());
            if (null == profit) {
                profit = new PlatformStrictProfit();
            }
            profit.setUserId(item.getId());

            List<UsersBalanceRecordStatistics> matchStatistics = list.stream().filter(s -> s.getUserId().equals(item.getId())).collect(Collectors.toList());
            if (CollectionUtils.isEmpty(matchStatistics)) {
                profit.setIncomeRank(1);
            }else {
                UsersBalanceRecordStatistics newestStatistics =  matchStatistics.get(0);
                if (null == newestStatistics.getIncomeAmount()) {
                    profit.setIncomeRank(1);
                }else {
                    BigDecimal rankResult = newestStatistics.getIncomeAmount().divide(new BigDecimal(incomeRankDayBaseValue), 4, BigDecimal.ROUND_HALF_UP);
                    profit.setIncomeRank(rankResult.multiply(new BigDecimal("100")).intValue());
                    if (profit.getIncomeRank() < 1) {
                        profit.setIncomeRank(1);
                    } else if (profit.getIncomeRank() > 99) {
                        profit.setIncomeRank(99);
                    }
                }
            }

            profit.setUpdateTime(new Date());
            if (null == profit.getId()) {
                platformStrictProfitMapper.insertSelective(profit);
            }else {
                platformStrictProfitMapper.updateByPrimaryKey(profit);
            }
        });
    }
}
